﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;
using Mysqlx;
using Google.Protobuf.WellKnownTypes;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    ///  CRM送货单扫描上传
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CRMSignUploadController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;
        public readonly string con_oa;


        public CRMSignUploadController(ILogger<CRMSignUploadRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_oa = _configuration.GetConnectionString("OA_DbConnection");
            _logger = loggerFactory.CreateLogger<CRMSignUploadController>();
        }

        /// <summary>
        /// CRM送货单扫描上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostSignUpload([FromBody] CRMSignUploadRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            CRMSignUploadResponseDto re = new CRMSignUploadResponseDto();
            string ddm_token_crm = "&token=eyJ4ZGFwdGVuYW50aWQiOiIzMzk4MTY5MTc5MDY3NTE0ODkiLCJ4ZGFwdGltZXN0YW1wIjoiMTc1MTMzODExOTAwMCJ9&download=download&formId=685cfa1f9dce705175948c57&uuid=80214dad8c6e29b1716047bb";

            try
            {
                dic = new Dictionary<string, string>();
                dic.Add("source_no", strparm.source_no);
                DataTable ma_dt = MethodHelp.GetTableInfo("TMS0203", dic, con);//获取待运算数据
                if (ma_dt.Rows.Count > 0)
                {
                    foreach (DataRow item in ma_dt.Rows)
                    {
                        string is_push = "";
                        string is_finish = "";
                        string fail_reason = "";
                        dic = new Dictionary<string, string>();
                        dic.Add("source_no", item["source_no"].ToString());
                        DataTable zt_dt = MethodHelp.GetTableInfo("TMS0204", dic, con);//获取待运算数据
                        if (zt_dt.Rows.Count > 0)
                        {
                            dic = new Dictionary<string, string>();
                            dic.Add("first_data", item["source_no"].ToString());
                            DataTable check_cc = MethodHelp.GetTableInfo("TMS0205", dic,con);
                            if (check_cc.Rows.Count>0)
                            {
                                if (check_cc.Rows[0]["node_title"].ToString()== "上传签收单")
                                {
                                    CRM_SC_RequestDto data_input = new CRM_SC_RequestDto();//operationinfo赋值
                                    List<CRM_SC_DataRequestDto> input_fj = new List<CRM_SC_DataRequestDto>();//operationinfo赋值
                                    var fj = JsonConvert.DeserializeObject<DDM__adjunct[]>(ma_dt.Rows[0]["order_adjunct"].ToString());
                                    if (fj != null)
                                    {
                                        foreach (var rows in fj)
                                        {
                                            //mainTable_input赋值
                                            input_fj.Add(new CRM_SC_DataRequestDto
                                            {
                                                url = rows.url + ddm_token_crm
                                            });
                                        }

                                        Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                                        urldic.Add("function_description", "CRM自提签收单上传");//查看URL配置表地址描述
                                        DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                        if (url_dt.Rows.Count > 0)
                                        {
                                            data_input.djh = ma_dt.Rows[0]["source_no"].ToString();
                                            data_input.fileUrlList = input_fj;
                                            string jsonText = JsonConvert.SerializeObject(data_input);
                                            var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                            CRM_SC_ResponseDto psp = JsonConvert.DeserializeObject<CRM_SC_ResponseDto>(reAgv);
                                            if (psp.code.Contains("error"))
                                            {
                                                strMsg = "签收回传异常，原因：" + psp.message;
                                            }
                                        }


                                    }
                                }else 
                                {
                                    if (check_cc.Rows[0]["node_title"].ToString()== "结束")
                                    {
                                        fail_reason = "拆车单=<" + item["source_no"].ToString() + ">流程已经完成，无需继续更新！";
                                        is_push = "N";
                                        is_finish = "Y";
                                    }
                                    else
                                    {
                                        fail_reason = "拆车单=<" + item["source_no"].ToString() + ">未到达上传节点，等待到达后重传！";
                                        is_push = "N";
                                        is_finish = "N";
                                    }
                                }
                               
                            }
                            else
                            {
                                fail_reason = "找不到拆车单=<"+ item["source_no"].ToString() + ">相关流程数据！";
                                is_push = "N";
                                is_finish = "Y";
                            }                           
                        }
                        else
                        {
                            fail_reason = "签收回传异常，找不到自提单号=<" + ma_dt.Rows[0]["source_no"].ToString() + ">数据！";
                            is_push = "N";
                            is_finish = "Y";
                        }

                        dic = new Dictionary<string, string>();
                        dic.Add("is_push", is_push);
                        dic.Add("is_finish", is_finish);
                        dic.Add("fail_reason", fail_reason);
                        dic.Add("source_no", item["source_no"].ToString());
                        string sqlstr = MethodHelp.GetTranSQL("TMS0206", dic, con);//状态结果更新语句
                        if (sqlstr != "")
                        {
                            strSqlList.Add(sqlstr);
                        }
                    }

                    if (strSqlList.Count>0&&strMsg=="")
                    {
                        bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                        if (A)
                        {

                        }
                        else
                        {
                            strMsg = "Database update failed";
                        }
                    }
                }               
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            //_logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
